package com.linwen.excise.base;

/**
 * @author : linwen
 * @date : 下午3:05 2021/5/23
 */
/*
* 斐波那契额数列
* */
public class _02计算斐波那契数例第n个数 {
    public static void main(String[] args) {
        int n = 40;
        Long start = System.currentTimeMillis();
        System.out.println(fibonacci(n));
        System.out.println(System.currentTimeMillis()-start);
        start = System.currentTimeMillis();
        System.out.println(fibonacci1(n));
        System.out.println(System.currentTimeMillis()-start);

    }
    //递归解法
    private static int fibonacci(int n) {
        if(n<1){
            return -1;
        }else if(n==1||n==2){
            return 1;
        }else{
            return fibonacci(n-1)+fibonacci(n-2);
        }
    }
    //for解法
    private static int fibonacci1(int n) {
        int result = 0;
        if(n<1){
            result =  -1;
        }else if(n==1||n==2){
            result = 1;
        }else{
            int first=1,second=1;
            for (int i = 0; i <n-2; i++) {
                result = first+second;
                first = second;
                second = result;
            }
        }
        return result;
    }

}
